package xh.util;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * Created by xh on 2016/6/27.
 */
public class HttpUtils {

    private static FullHttpResponse defaultResponse(HttpResponseStatus hs) {
        return new DefaultFullHttpResponse(HTTP_1_1, hs, Unpooled.wrappedBuffer(hs.toString().getBytes()));
    }

    public static FullHttpResponse _404() {
        return defaultResponse(HttpResponseStatus.NOT_FOUND);
    }

    public static FullHttpResponse _500() {
        return defaultResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }

    public static FullHttpResponse jsonResponse(Object o) {
        ByteBuf bb = Unpooled.wrappedBuffer(JSON.toJSONString(o).getBytes(Global.DefaultCharset));
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, bb);
        response.headers().set(CONTENT_TYPE, "application/json;charset=UTF-8");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        return response;
    }
}
